package com.douyin.video.api;

import com.app.utils.JsonUtil;
import com.app.utils.Result;
import com.douyin.video.entity.DouyinVideo;
import com.douyin.video.service.DouyinVideoService;
import com.douyin.video.utils.DouYinUtil;
import com.sys.user.entity.SysUser;
import com.utils.DateFormatUtil;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * 抖音视频
 *
 *
 * @author djianfeng
 * @since 2018-08-27
 */
@RestController
@RequestMapping("/dy/api")
@Slf4j
public class DouyinVideoControllerApi {
	
	@Autowired
	DouyinVideoService douyinVideoService;
	
	@Value("${dyVideo}")
	private String dyVideo;
	

	/**
	 * 解析视频并获取Json数据
	 * 
	 * @param response
	 * @param shareUrl
	 * @return
	 */
	@RequestMapping(value = "/getVideo.do", method = RequestMethod.POST)
	@ResponseBody
	public Result getVideo(HttpServletRequest request, HttpServletResponse response, String shareUrl) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		if (StringUtils.isBlank(shareUrl)) {
			return Result.returnError("视频分享链接不能为空");
		}

		DouyinVideo view = DouYinUtil.video(shareUrl);
		if (view != null) {
			Subject currentUser = SecurityUtils.getSubject();
			SysUser user = (SysUser) currentUser.getPrincipal();
			if (user != null) {
				view.setUserId(user.getId());
			}
			DouyinVideo douyinVideo = DouYinUtil.downloadVideo(shareUrl, dyVideo,request, response);
			if (douyinVideo!=null) {
				view.setWatermarkUrl(douyinVideo.getWatermarkUrl());
				view.setWatermarkVideo(douyinVideo.getWatermarkVideo());
			} else {
				return Result.returnError("解析失败");
			}
			view.setCreateTime(DateFormatUtil.getStringDateYMDHMS());
			view.setExtendInfo(JsonUtil.formatToStr(view));
			view.setUrl(shareUrl);
			this.douyinVideoService.insert(view);
			return Result.returnSuccess(view);
		}
		return Result.returnError("解析失败");
	}

	/**
	 * 下载视频
	 * 
	 * @param response
	 * @param shareUrl
	 * @return
	 */
	@RequestMapping(value = "/analysisVideo.do", method = RequestMethod.POST)
	@ResponseBody
	public Result downloadVideo(HttpServletRequest request, HttpServletResponse response, String url) {
		DouyinVideo douyinVideo = douyinVideoService.queryDouyinVideoByUrl(url);
		
		DouyinVideo view = DouYinUtil.downloadVideo(url,dyVideo, request, response);
		if (view!=null) {
			douyinVideo.setWatermarkUrl(view.getWatermarkUrl());
			douyinVideo.setWatermarkVideo(view.getWatermarkVideo());
		}else{
			return Result.returnError("解析失败");
		}
		
		Subject currentUser = SecurityUtils.getSubject();
		SysUser user = (SysUser) currentUser.getPrincipal();
		if (user != null) {
			douyinVideo.setUserId(user.getId());
		}
		douyinVideoService.updateById(douyinVideo);
		return Result.returnSuccess("success");

	}

	
	//角色 加 路径 拦截器  
	@RequestMapping("/downloadFile")
    private void downloadFile(String url,HttpServletResponse response){
//		String downloadFilePath = "/root/fileSavePath/";//被下载的文件在服务器中的路径,
//		String fileName = "demo.xml";//被下载文件的名称   
		File file = new File(url);
//		if (file.exists()) {
		response.setContentType("application/force-download");// 设置强制下载不打开            
		response.addHeader("Content-Disposition", "attachment;fileName=" + DouYinUtil.getRandomString(20)+".mp4");
		byte[] buffer = new byte[1024];
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			OutputStream outputStream = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
			outputStream.write(buffer, 0, i);
			i = bis.read(buffer);
		}
		} catch (Exception e) {
			log.info("发生错误:"+e);
		} finally {
			if (bis != null) {
				try {
					bis.close();
					} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				e.printStackTrace();
			}
		}
		}
//		}
    }

}
